<template>
  <el-card>
    <el-form class="form" :inline="true">
      <el-form-item label="用户名">
        <el-input
          v-model="searchValue"
          style="width: 240px"
          placeholder="输入用户名"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" :disabled="!searchValue">
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card style="margin: 15px 0 0 0">
    <div>
      <el-button
        @click="addRole"
        v-has="'btn.Role.add'"
        type="primary"
        icon="Plus"
      >
        添加职位
      </el-button>
    </div>
    <el-table style="margin-top: 15px" :data="roleList" border>
      <el-table-column label="#" type="index" align="center"></el-table-column>
      <el-table-column label="id" prop="id" width="80"></el-table-column>
      <el-table-column
        label="角色名称"
        prop="roleName"
        width="160"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="320" align="center">
        <template #="{ row, index }">
          <div>
            <el-button
              type="primary"
              icon="User"
              @click="manageRole(row)"
              v-has="'btn.Role.assgin'"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              icon="Edit"
              @click="editRole(row)"
              v-has="'btn.Role.update'"
            >
              编辑
            </el-button>

            <el-popconfirm
              title="确定删除该角色吗"
              @confirm="confirmDelete(row)"
            >
              <template #reference>
                <el-button
                  v-has="'btn.Role.remove'"
                  type="primary"
                  icon="Delete"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 25px"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 12]"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @size-change="getRoleListFromServer"
      @current-change="getRoleListFromServer"
    />
  </el-card>

  <el-dialog
    v-model="dialogVisible"
    :title="roleParam.id ? '更新职位' : '添加职位'"
    width="500"
  >
    <el-form ref="ruleFormRef" :model="roleParam" :rules="rule">
      <el-form-item prop="roleName" label="职位名称">
        <el-input
          v-model="roleParam.roleName"
          placeholder="请输入职位名称"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddRole">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-drawer v-model="manageRoelDrawer" :direction="'rtl'">
    <template #header>
      <h4>分配权限</h4>
    </template>
    <template #default>
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="roleMenuTreeData"
        :default-checked-keys="selectIds"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="defaultProps"
      />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="manageRoelDrawer = false">取消</el-button>
        <el-button type="primary" @click="confirmManageRole">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import {
  reqAllMenuTree,
  reqDeleteRole,
  reqRoleList,
  reqUpdateRole,
} from '@/api/user/role'
import { IRole, IRoleData } from '@/api/user/role/type'
import { ElMessage, FormInstance } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { ElTree } from 'element-plus'
import { reqDoAssign } from '@/api/user/role'
const defaultProps = {
  children: 'children',
  label: 'name',
}

let roleMenuTreeData = ref<IRole[]>([])
let manageRoelDrawer = ref<boolean>(false)
let currentPage = ref<number>(1)
let total = ref<number>(10)
let pageSize = ref<number>(5)
let searchValue = ref<string>('')
const ruleFormRef = ref<FormInstance>()
let roleList = ref<IRoleData[]>([])
let selectIds = ref([])
let roleParam = ref({
  roleName: '',
  id: '',
})
const treeRef = ref<InstanceType<typeof ElTree>>()
const confirmManageRole = () => {
  try {
    let ids1 = treeRef.value.getHalfCheckedKeys()
    let ids2 = treeRef.value.getCheckedKeys()
    let param = [...ids1, ...ids2]
    reqDoAssign(roleParam.value.id, param).then((res) => {
      ElMessage({
        type: 'success',
        message: '成功',
      })
      selectIds.value = []
      manageRoelDrawer.value = false
    })
  } catch (error) {
    console.log(error)
  }
}
const rule = {
  roleName: [
    { required: true, message: '此为必填项', trigger: 'blur' },
    { min: 2, max: 11, message: '应为2-11位', trigger: 'blur' },
  ],
}
let dialogVisible = ref(false)
const search = async () => {
  try {
    let result = await reqRoleList(
      currentPage.value,
      pageSize.value,
      searchValue.value,
    )
    if (result.code == 200) {
      roleList.value = result.data.records
      total.value = result.data.total
    }
  } catch (error) {
    console.log(error)
  }
}

onMounted(() => {
  getRoleListFromServer()
})
const manageRole = async (data) => {
  console.log(data)
  selectIds.value = []
  roleParam.value = data

  manageRoelDrawer.value = true
  try {
    let result = await reqAllMenuTree(data.id)
    if (result.code == 200) {
      roleMenuTreeData.value = result.data
      initSelectIds(result.data, selectIds.value)
      console.log(selectIds.value)
    }
  } catch (error) {
    console.log(error)
  }
}
const addRole = () => {
  ruleFormRef.value?.clearValidate()
  clearRoleParam()
  dialogVisible.value = true
}
const reset = () => {
  searchValue.value = ''
  getRoleListFromServer()
}
const editRole = (data) => {
  dialogVisible.value = true

  roleParam.value.id = data.id
  roleParam.value.roleName = data.roleName
}
const confirmAddRole = async () => {
  ruleFormRef.value.validate().then(async (res) => {
    try {
      let result = await reqUpdateRole(roleParam.value)
      if (result.code == 200) {
        dialogVisible.value = false
        getRoleListFromServer()
        ElMessage({
          type: 'success',
          message: roleParam.value.id ? '更新成功' : '添加成功',
        })
      }
    } catch (error) {
      console.log(error)
    }
  })
}
const clearRoleParam = () => {
  Object.assign(roleParam.value, {
    roleName: '',
    id: '',
  })
}
const getRoleListFromServer = async () => {
  try {
    let result = await reqRoleList(currentPage.value, pageSize.value)
    if (result.code == 200) {
      roleList.value = result.data.records
      total.value = result.data.total
    }
  } catch (error) {
    console.log(error)
  }
}

const initSelectIds = (TreeData: IRole[], initArray) => {
  TreeData.forEach((item) => {
    if (item.children && item.level != 4 && item.children.length != 0) {
      initSelectIds(item.children, initArray)
    } else if (item.select) {
      initArray.push(item.id)
    }
  })
}

const confirmDelete = async (data) => {
  try {
    let result = await reqDeleteRole(data.id)
    if (result.code == 200) {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      getRoleListFromServer()
    }
  } catch (error) {
    console.log(error)
  }
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .el-form-item {
    margin: 0;
  }
}
</style>
